import asyncio
import time

import websockets


# 处理websocket连接请求的协程函数
async def handler(websocket):
    print(f"[{time.asctime()} connection established]")
    async for message in websocket:
        print(f"[{time.asctime()} from client] {message}")
        await websocket.send(message)


# 开启服务器的协程函数

async def start_s():
    # 通过websockets库创建服务器，并指定协议、IP地址和端口号
    async with websockets.serve(handler, "localhost", 8765, ping_interval=200, ping_timeout=200, timeout=2000):
        print(f"{time.asctime()}[Server Started]")

        await asyncio.Future()  # 通过返回一个永久等待的协程，让协程函数一直运行


if __name__ == '__main__':
    asyncio.run(start_s())


